/*
 * @Author: your name
 * @Date: 2022-02-15 02:00:03
 * @LastEditTime: 2022-03-10 11:01:51
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /gomeshsync/core/dirfiles/dirfiles.go
 */
package dirfiles

import (
	"gomeshsync/config"
	"io/ioutil"
	"os"

	"gitee.com/kimsoso/go-utils/utils"
	"github.com/vmihailenco/msgpack"
)

type dirfile struct {
	Path     string `yaml:"path"`
	Size     int64  `yaml:"size"`
	FileMask string `yaml:"fileMask"`
	Done     bool   `yaml:"done"`
	DoneTime int64  `yaml:"doneTime"`
}

type dirFiles struct {
	files map[string]*dirfile
}

var (
	dirFilePath = config.DirCmds + ".files.yaml"
)

func CreateDirfile() *dirFiles {
	return &dirFiles{}
}

func (d *dirFiles) Files() map[string]*dirfile {
	return d.files
}

func (d *dirFiles) Len() int {
	return len(d.files)
}

func (d *dirFiles) AddFile(df *dirfile) {
	if _, ok := d.files[df.Path]; ok {
		return
	}
	d.files[df.Path] = df
	tmp := map[string]*dirfile{}
	tmp[df.Path] = df
	buf, _ := msgpack.Marshal(tmp)
	utils.AppendFile(dirFilePath, buf)
}

func (d *dirFiles) Save() {
	buf, _ := msgpack.Marshal(d.files)
	utils.WriteFile(dirFilePath, buf, os.ModePerm)
}

func (d *dirFiles) Load() {
	buf, err := ioutil.ReadFile(dirFilePath)
	if err == nil {
		msgpack.Unmarshal(buf, &d.files)
	}
}
func (d *dirFiles) SetFileMask(filePath string, idx int, dim string) {
	if file, ok := d.files[filePath]; ok {
		file.FileMask = file.FileMask[:idx] + dim + file.FileMask[idx+1:]
		d.Save()
	}
}
